﻿using GMall.AdministrationService.Menus;
using GMall.AdministrationService.Permissions.Dtos;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Identity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.SimpleStateChecking;

namespace GMall.AdministrationService.Permissions
{
    public class PermissionAppService : Volo.Abp.PermissionManagement.PermissionAppService, IPermissionAppService
    {
        private readonly IdentityUserManager _identityUserManager;
        private readonly IPermissionGrantRepository _permissionGrantRepository;
        public PermissionAppService(IPermissionManager permissionManager, IPermissionDefinitionManager permissionDefinitionManager, IOptions<PermissionManagementOptions> options, ISimpleStateCheckerManager<PermissionDefinition> simpleStateCheckerManager, IPermissionGrantRepository permissionGrantRepository) : base(permissionManager, permissionDefinitionManager, options, simpleStateCheckerManager)
        {
            _permissionGrantRepository = permissionGrantRepository;
        }
        [RemoteService(false)]
        public virtual async Task<List<string>> GetGrantedListAsync(PermissionGetGrantedListInput input)
        {
            var result = new List<string>();
            if (input.RoleId.HasValue)
            {
                var permissionList = await _permissionGrantRepository.GetListAsync("R", input.RoleId.Value.ToString());
                if (permissionList?.Any() ?? false)
                {
                    result.AddRange(permissionList.Select(p => p.Name));
                }
            }
            if (input.UserId.HasValue)
            {
                var user = await _identityUserManager.GetByIdAsync(input.UserId.Value);
                foreach (var role in user.Roles)
                {
                    var permissionList = await _permissionGrantRepository.GetListAsync("R", role.RoleId.ToString());
                    if (permissionList?.Any() ?? false)
                    {
                        result.AddRange(permissionList.Select(p => p.Name));
                    }
                }
            }
            result = result.Distinct().ToList();
            return result;
        }

    }
}
